const mongoose =require('mongoose'); 
const mongoDB_URL="mongodb://localhost/test";

var db=mongoose.connection;
db.on("error",function(){
    console.log("连接出错了");
});

db.on("open",function(){
    console.log("连接成功了");
});

mongoose.connect(mongoDB_URL,{
    useUnifiedTopology: true,
    useNewUrlParser: true
});

var personSchema= mongoose.Schema({
    name: String,
    age: Number,
    sex: {
        type: String,
        default: "男"
    }
});

var Person=mongoose.model("Person",personSchema,"Person");

var person=new Person({
    name:"Jaasdsa",
    age: 18,
})

// 增
person.save(function(err,product){
    if(err) console.log(err);
    console.log("保存成功了",product);
})

// 查
Person.find({name: "jack"},function(err,res){
    if(err) console.log(err);
    console.log("查询成功了",res);
})

// 条件查
Person.find({name:'jack',age: {$lt: 19}},function(err,res){
    if(err) console.log(err);
    console.log("小于查询成功了",res);
})

// 删除
// Person.remove({name:'1111111'},function(err,res){
//     if(err) console.log(err);
//     console.log("删除成功了",res);
// })

// 更新
Person.update({name: 'Jaasdsa'},{name: '1111111'},{multi:true},function(err,res){
    if(err) console.log(err);
    console.log("更新成功了",res);
})

setTimeout(() => {
    console.log("主动断开");
    mongoose.disconnect(); 
}, 5000);
